source('codes/00_import_libraries.R')


#------------------------------------------------------------------------
# Specifications
#------------------------------------------------------------------------

dict_name = 'base'
win       = 120
beg_year  = 1881


narrative_dicts = readRDS('input/narrative_dicts_v2.rds')
topic_list      = narrative_dicts[[dict_name]] %>% names() %>% 
  str_replace_all('_', ' ') %>% tools::toTitleCase()


gw_names = readRDS('input/gw_macro_predictors.RDS')$macro_names
names(gw_names) = readRDS('input/gw_macro_predictors.RDS')$macro_list
gw_list = c('DP', 'DY', 'EP', 'DE', 'SVAR', 'TBL')
gw_names = gw_names[gw_list]


rowname_list = list(
  `Panel A: OLS` = c(gw_names, topic_list),
  `Panel B: PLS` = c('Economic', 'All Topics', 'Shiller Topics')
)


year_grid = data.frame(
  beg = c(beg_year, beg_year, 1950, 2000),
  end = c(2019, 1949, 2019, 2019)
)
period_list = paste0(year_grid$beg, '-', year_grid$end)



#------------------------------------------------------------------------
# File list
#------------------------------------------------------------------------

file_list = paste0(
  'output/os/',
  c(glue('ols_mkt1_{win}.rds'), 
    glue('pls_mkt1_{win}.rds'))
)



#------------------------------------------------------------------------
# R2
#------------------------------------------------------------------------

#----------------------------#
#----- function -------------#
#----------------------------#

fn_return_r2 = function(file) {

  readRDS(file) %>% 
  
  lapply(function(df) {
    df = df %>% mutate(year = year(ym))
    
    sapply(1:nrow(year_grid), function(i) {
      fn_star_os_r2(df = df, h = 1, year_grid$beg[i]:year_grid$end[i])
    })  
  })
}



#----------------------------#
#----- r2 -------------------#
#----------------------------#

output = lapply(seq_along(file_list), function(i) {
  
  fn_return_r2(file_list[i]) %>% 
    do.call(what = rbind) %>% 
    as_hux() %>% 
    insert_column(rowname_list[[i]]) %>% 
    insert_row(names(rowname_list)[i], fill = '') %>% 
    set_top_border(1, everywhere, 0.8) %>% 
    set_bottom_border(final(1), everywhere, 0.8)

}) %>% 

  do.call(what = rbind) %>% 
  insert_row(c('', period_list)) %>% 
  set_tb_borders(1, everywhere, 0.8) %>% 
  set_number_format(1, everywhere, 0) %>% 
  set_number_format(-1, -1, 2) %>% 
  set_align(1, everywhere, 'center') %>% 
  set_align(-1, -1, '.') %>% 
  set_tb_padding(0) %>% 
  set_lr_padding(5) |> 
    insert_row(after = 8, fill = '')



#------------------------------------------------------------------------
# Export
#------------------------------------------------------------------------

quick_xlsx(output, file = 'output/tables/Table_8.xlsx')
# cat(to_latex(output, tabular_only = TRUE), file = glue('output/tables/Table_8.xlsx'))

  
  
